<template>
  <view>
    <view
      class="top navbar"
      :style="{
        paddingTop: safeArea?.top + 'px',
        height: view.topBar.height + 'px'
      }"
    >
      <view @click="toBack" class="back icon-left">
        <uni-icons type="left" size="20"></uni-icons>
      </view>
      <span class="title">{{ shopInfo?.name }}</span>
    </view>
    <scroll-view enable-back-to-top scroll-y id="scroller">
      <view
        class="header"
        :style="{
          paddingTop: safeArea.completeTop + 'px',
          height: shopInfoTopBtnRowHeight + shopDescHeight + 'px',
          backgroundSize: `100% ${safeArea.completeTop + shopInfoTopBtnRowHeight + shopDescHeight * 0.5}px`,
          backgroundImage: `url('${shopInfo?.backgroundPoster}')`
        }"
      >
        <view class="top-btn-row" :style="{ height: shopInfoTopBtnRowHeight + 'px' }">
          <span class="icon-btn button-pressing" @click="followOrUnFollowShop(shopInfo?.isFollow)">
            <uni-icons
              :type="shopInfo?.isFollow ? 'star-filled' : 'star'"
              size="25"
              :color="shopInfo?.isFollow ? '#fcde00' : '#fff'"
            ></uni-icons>
          </span>

          <button class="icon-btn button-pressing share" open-type="share" v-if="!shopStore.isGuest.value">
            <uni-icons type="personadd" size="25" color="#fff"></uni-icons>
          </button>
          <span class="icon-btn button-pressing"><uni-icons type="redo" size="25" color="#fff"></uni-icons></span>
        </view>
        <view class="shop-desc" :style="{ height: shopDescHeight + 'px' }">
          <view class="left-info">
            <view class="shop-info-row1">
              <span class="shop-name">{{ shopInfo?.name }}</span>
              <span
                class="reputation"
                :style="{
                  background: reputationColorOf(shopInfo?.reputation)
                }"
                >{{ reputationLabelOf(shopInfo?.reputation) }}</span
              >
            </view>
            <view class="shop-info-row2">
              <span class="business-status" :style="{ color: businessStatusColorOf(shopInfo?.businessStatus) }">{{
                businessStatusLabelOf(shopInfo?.businessStatus)
              }}</span>
              <span class="separate-line">|</span>
              <span class="notice">
                <uni-icons type="sound" size="20" color="#7f7f7f"></uni-icons>
                <span class="notice-text">{{ shopInfo?.notice }}</span>
              </span>
            </view>

            <view class="shop-info-row3">
              <view
                class="x-rol"
                v-if="
                  applicableShopPreferential?.activityLabels != null &&
                  applicableShopPreferential?.activityLabels.length > 0
                "
              >
                <view class="rol">
                  <span
                    class="activity-item"
                    v-for="(activityLabel, index) in applicableShopPreferential?.activityLabels"
                    :key="index"
                    >{{ activityLabel.join(' | ') }}</span
                  >
                </view>
              </view>
              <view class="x-rol" style="margin-top: 5rpx">
                <view class="rol">
                  <template
                    v-if="
                      applicableShopPreferential?.platformCouponList != null &&
                      applicableShopPreferential?.platformCouponList.length > 0
                    "
                  >
                    <coupon-button
                      v-for="(couponCoreInfo, index) in applicableShopPreferential?.platformCouponList"
                      :key="index"
                      :data="couponCoreInfo"
                    ></coupon-button>
                  </template>
                  <template
                    v-if="
                      applicableShopPreferential?.shopCouponList != null &&
                      applicableShopPreferential?.shopCouponList.length > 0
                    "
                  >
                    <coupon-button
                      v-for="(couponCoreInfo, index) in applicableShopPreferential?.shopCouponList"
                      :key="'2-' + index"
                      :data="couponCoreInfo"
                    ></coupon-button>
                  </template>
                </view>
              </view>
            </view>
          </view>
          <view class="right-info">
            <image class="logo" :src="shopInfo?.logo" />
          </view>
        </view>
      </view>
      <view
        class="body"
        :style="{
          // 为阴影向上偏移3px
          height: view.height - safeArea.completeTop + 3 + 'px'
        }"
      >
        <shop-nav class="box-nav" v-model="currentNav"></shop-nav>
        <view class="nav-view">
          <dish-category-view
            :data="shopInfo?.dishCategoryList"
            :shopId="$props.shopId"
            :positioning-dish-category-id="$props.dishCategoryId"
            :positioning-dish-id="$props.dishId"
            v-show="currentNav === 0"
          ></dish-category-view>
          <shop-evaluation-view v-show="currentNav === 1"></shop-evaluation-view>
          <shop-info-view v-show="currentNav === 2"></shop-info-view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { computed, onMounted, provide, ref } from 'vue'
import $store from '@/store'
import $API from '@/api'
import type { ShopInfo, ShopPreferentialLabelInfoVO } from '@/types/response/shop'
import { onReady } from '@dcloudio/uni-app'
import ShopNav from './components/nav/index.vue'
import DishCategoryView from './components/views/main/index.vue'
import ShopInfoView from './components/views/shop-info/index.vue'
import ShopEvaluationView from './components/views/evaluation/index.vue'
import CouponButton from '@/components/coupon-button/index.vue'
import { CouponType } from '@/enum/CouponType'
import { useShare } from '@/hooks/useShare'
import { reputationColorOf, reputationLabelOf } from '@/enum/ReputationMap'
import { businessStatusColorOf, businessStatusLabelOf } from '@/enum/BusinessStatus'

const shopInfoTopBtnRowHeight = 40
const shopInfoTopBtnRowIconHeight = computed(() => shopInfoTopBtnRowHeight + 'px')
const shopDescHeight = 137
const shopStore = $store.shop
const { safeArea, capsule, view } = $store.app.getSystemParam()
// 接收页面参数
const query = defineProps<{
  shopId: number
  dishCategoryId?: number
  dishId?: number
  seatNumber?: string
  inviteCode?: string
}>()
console.log('query=', query)
onMounted(() => {
  // 将场景参数放进store中（页数据）
  queryProcessHandler()
  getShopInfoById()
  getRequireInfo()
})

async function queryProcessHandler() {
  shopStore.shopId.setValue(parseInt(query.shopId + '') || undefined)
  shopStore.seatNumber.setValue(query.seatNumber)
  shopStore.inviteCode.setValue(query.inviteCode)

  // 如果邀请码是自己的就是邀请者（Inviter）
  const { data } = await $API.shop.getMyOrderingInvitationCode(shopStore.shopId.getValue()!)
  shopStore.isInviter.setValue(data != null && (data == query.inviteCode || !query.inviteCode))
  console.log('isInviter=', data, query.inviteCode, '结果=', shopStore.isInviter.getValue())
  shopStore.inviteCode.setIfAbsent(data)
}
// 返回上一层（这里需要使用API方式，因为触发pageData清理需要手动的方式才能拦截）
function toBack() {
  uni.navigateBack()
}

// 获取页面栈
const pages = getCurrentPages()

// 基于小程序的 Page 类型扩展 uni-app 的 Page
type PageInstance = Page.PageInstance & WechatMiniprogram.Page.InstanceMethods<any>

// #ifdef MP-WEIXIN
// 获取当前页面实例，数组最后一项
const pageInstance = pages.at(-1) as PageInstance

// 页面渲染完毕，绑定动画效果
onReady(() => {
  // 动画效果,导航栏背景色
  pageInstance.animate('.navbar', [{ backgroundColor: 'transparent' }, { backgroundColor: '#fff' }], 1000, {
    scrollSource: '#scroller',
    timeRange: 1000,
    startScrollOffset: 0,
    endScrollOffset: safeArea.completeTop + capsule.spacingBotton + shopInfoTopBtnRowHeight
  })
  // 标题
  pageInstance.animate('.title', [{ color: 'transparent' }, { color: '#000' }], 1000, {
    scrollSource: '#scroller',
    timeRange: 1000,
    startScrollOffset: 0,
    endScrollOffset: safeArea.completeTop + capsule.spacingBotton + shopInfoTopBtnRowHeight
  })
  // 动画效果,导航栏返回按钮
  pageInstance.animate('.back', [{ color: '#fff' }, { color: '#000' }], 1000, {
    scrollSource: '#scroller',
    timeRange: 1000,
    startScrollOffset: 0,
    endScrollOffset: safeArea.completeTop + capsule.spacingBotton + shopInfoTopBtnRowHeight
  })
})
// #endif
// 请求店铺的数据
const shopInfo = ref<ShopInfo>()
async function getShopInfoById() {
  const result = await $API.shop.getShopInfoById(query.shopId)
  if (result.success) shopInfo.value = result.data
}
const applicableShopPreferential = ref<ShopPreferentialLabelInfoVO>()
async function getRequireInfo() {
  const result = await $API.shop.getApplicableShopPreferential(query.shopId)
  // 设置前端组件需要的值
  if (result.success) {
    // 平台券设置需要的参数
    ;(result.data.platformCouponList ?? []).forEach((element) => {
      element._isDiscountValue = element.type === CouponType.DISCOUNT_COUPON
      element._isPlatformCoupon = true
    })
    // 店铺券设置需要的参数
    ;(result.data.shopCouponList ?? []).forEach((element) => {
      element._isDiscountValue = element.type === CouponType.DISCOUNT_COUPON
      element._isPlatformCoupon = false
    })
  }
  applicableShopPreferential.value = result.data
}
// 关注或取消关注店铺
async function followOrUnFollowShop(currentIsFollow?: boolean) {
  if (currentIsFollow === undefined || currentIsFollow === null) return
  const changeAfterIsFollow = !currentIsFollow
  const result = await $API.shopCollect.followUnfollowShop(query.shopId, changeAfterIsFollow)
  if (result.success) shopInfo.value!.isFollow = changeAfterIsFollow
}
// 获取店铺信息
function getShopInfo() {
  return shopInfo.value
}
// 获取店铺优惠信息
function getShopPreferential() {
  return applicableShopPreferential.value
}
// 获取店铺优惠信息
function getShopPreferentialLabelInfoVO() {
  return applicableShopPreferential.value
}

useShare(async function onShareAppMessage() {
  // 请求点餐邀请码
  const result = await $API.shop.inviteFriends(query.shopId)
  shopStore.inviteCode.setValue(result.data)
  shopStore.isInviter.setValue(true)
  return {
    title: shopInfo.value?.name || '和我一起点餐吧！', // 使用店铺名称作为标题
    desc: '邀请你一起点餐~',
    path: `/pages/shop/index?shopId=${query.shopId}&inviteCode=${result.data}`, // 分享路径
    imageUrl: shopInfo.value?.logo || '', // 使用店铺logo作为分享图片
    success() {
      uni.showToast({
        title: '分享成功',
        icon: 'success',
        duration: 2000
      })
    },
    fail() {
      console.log('分享失败')
      uni.showToast({
        title: '分享失败',
        icon: 'none',
        duration: 2000
      })
    }
  }
})
// function shareToWeChat() {
//   uni.share({
//     provider: 'weixin',
//     type: 0, // 0表示图文
//     title: '和我一起点餐吧！',
//     summary: '一起点餐',
//     href: `/pages/index/index?shopId=${query.shopId}&inviteCode=testInviteId`, // 分享的路径
//     // imageUrl: 'https://example.com/image.png', // 分享的图片
//     success() {
//       uni.showToast({
//         title: '分享成功',
//         icon: 'success',
//         duration: 2000
//       })
//     },
//     fail(e) {
//       console.log('分享失败', e)
//       uni.showToast({
//         title: '分享失败',
//         icon: 'none',
//         duration: 2000
//       })
//     }
//   })
// }

// 向下共享店铺信息
provide('shopInfo', shopInfo)
const currentNav = ref(0)
</script>

<style scoped lang="scss">
$shop-desc-height: 240rpx;
$shop-logo-size: $shop-desc-height * 0.75;
$plate-width: 750rpx * 0.9;
$plate-padding-size: 30rpx;
$right-margin-size: 15rpx;
$shop-left-info-width: $plate-width - $shop-logo-size - $plate-padding-size * 2 - $right-margin-size;

.top {
  position: fixed;
  z-index: 100;
  display: flex;
  align-items: center;
  width: 100vw;

  .back {
    display: inline-block;
    margin: 0 20rpx;
    padding: 10rpx;
    border-radius: 50%;
  }

  .title {
    font-size: 32rpx;
    color: #fff0;
  }
}

#scroller {
  width: 100vw;
  height: 100vh;

  .header {
    width: 100vw;
    background-repeat: no-repeat;
    background-origin: border-box;

    .top-btn-row {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 0 5%;
      width: 100%;
      box-sizing: border-box;

      .icon-btn {
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0 15rpx 0 0;
        height: v-bind(shopInfoTopBtnRowIconHeight);
        border: none;
        background: none;
        outline: none;
        transition: transform 0.2s ease-in-out; /* 添加过渡效果，缓动函数采用 ease-in-out */
        cursor: pointer;
        user-select: none; /* 防止选中文本 */
        // -webkit-appearance: none;
      }

      .icon-btn::after {
        border: none;
      }
    }

    .shop-desc {
      position: relative;
      display: flex;
      justify-content: space-between;
      margin: 0 auto;
      padding: $plate-padding-size;
      width: $plate-width;
      border-radius: 20rpx;
      background-color: #fff;
      box-shadow: 0 0 8px rgb(0 0 0 / 32%);
      box-sizing: border-box;

      .left-info {
        display: flex;
        width: $shop-left-info-width;
        flex-direction: column;

        .shop-info-row1 {
          display: flex;
          align-items: center;

          .shop-name {
            font-size: 16px;
            font-weight: 700;
            line-height: 27px;
          }

          .reputation {
            display: inline-block;
            margin: 0 15px;
            padding: 0rpx 7.5px;
            font-size: 11px;
            font-weight: 700;
            border-radius: 5px;
            color: #fff;
            line-height: 18px;
            box-sizing: border-box;
          }
        }

        .shop-info-row2 {
          $row2-height: 25px;
          $row2-font-size: $row2-height * 0.5;

          display: flex;
          align-items: center;
          overflow: hidden;
          height: $row2-height;
          font-size: $row2-font-size;
          text-overflow: ellipsis;
          white-space: nowrap;
          color: #6c6c6c;
          flex-shrink: 0;

          .business-status {
            font-weight: bold;
          }

          .separate-line {
            display: flex;
            align-items: center;
            padding: 0 6px;
            height: $row2-height;
            font-size: $row2-font-size * 0.7;
            line-height: $row2-height;
          }

          .notice {
            display: flex;
            align-items: center;
            overflow: hidden;
            font-size: $row2-font-size * 0.9;
            text-overflow: ellipsis;
            white-space: nowrap;

            .notice-text {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }

        .shop-info-row3 {
          position: relative;
          display: flex;
          width: 100%;
          flex-grow: 1;
          flex-direction: column;

          .x-rol {
            .activity-item {
              display: inline-block;
              margin-right: 3px;
              padding: 2px 5px;
              font-size: 10px;
              border: 1rpx solid #ff45458c;
              border-radius: 5px;
              color: #ff4545;
            }
          }

          .separator {
            display: flex;
            align-items: center;
            margin: 0 7.5px;
            font-size: 8px;
            font-weight: 700;
            color: rgb(255 137 137);
          }
        }
      }

      .right-info {
        display: flex;
        align-items: center;
        margin-left: $right-margin-size;
        width: $shop-logo-size;
        flex-shrink: 0;

        .logo {
          width: 100%;
          height: $shop-logo-size;
        }
      }
    }
  }

  .body {
    display: flex;
    width: 100%;
    flex-direction: column;

    .box-nav {
      display: block;
      padding: 0 6%;
      box-sizing: border-box;
      width: 100%;
      height: 50px;
      border-bottom: 2px solid #f5f5f5;
    }

    .nav-view {
      width: 100%;
      flex-grow: 1;
    }
  }
}
</style>
<style scoped lang="scss">
/* x轴滚动 */
.x-rol {
  position: relative;
  display: inline-block;
  overflow: scroll;
  flex-grow: 1;
  box-sizing: border-box;

  .rol {
    display: flex;
    align-items: center;
    height: 100%;

    /* 实现x轴实现的重要css */
    white-space: nowrap;
  }
}

.x-rol::-webkit-scrollbar {
  display: none;
}
</style>
